package yiran.dcolormotd.tool;

import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.CachedServerIcon;
import yiran.daobase.output.MessageUtils;
import yiran.dcolormotd.DColorMotd;
import yiran.dcolormotd.manager.ConfigManager;
import yiran.dcolormotd.manager.IconManager;
import yiran.dcolormotd.manager.MotdManager;
import yiran.daobase.lang.LangHelper;

public class ServerPingListener implements Listener {
    private final JavaPlugin plugin;
    private final ConfigManager configManager;
    private final IconManager iconManager;
    private final MotdManager motdManager;

    public ServerPingListener(JavaPlugin plugin, ConfigManager configManager,
                             IconManager iconManager, MotdManager motdManager) {
        this.plugin = plugin;
        this.configManager = configManager;
        this.iconManager = iconManager;
        this.motdManager = motdManager;
    }

    @EventHandler
    public void onServerListPing(ServerListPingEvent event) {
        // 设置MOTD
        event.setMotd(motdManager.getProcessedMotd());

        // 设置服务器图标（1.7.10+支持）
        if (DColorMotd.isVersionAtLeast(1, 7)) {
            String iconType = getServerStatus();
            CachedServerIcon icon = iconManager.getIcon(iconType);

            if (icon != null) {
                try {
                    event.setServerIcon(icon);
                } catch (Exception e) {
                    MessageUtils.log("error", LangHelper.getString("set_icon_failed", e.getMessage()));
                }
            }
        }
    }

    private String getServerStatus() {
        FileConfiguration config = configManager.getConfig();

        if (config.getBoolean("maintenance_mode", false)) {
            return "maintenance";
        }
        else if (isServerStarting()) {
            return "starting";
        }
        else if (DColorMotd.getOnlinePlayersCount() >= plugin.getServer().getMaxPlayers()) {
            return "full";
        }
        
        return "normal";
    }

    private boolean isServerStarting() {
        long startingDuration = configManager.getConfig().getLong("starting_duration", 30) * 1000;
        return (System.currentTimeMillis() - ((DColorMotd) plugin).getServerStartTime()) < startingDuration;
    }
}
